import { Button, Card, Space, message } from 'antd';
import {
  CommonForm,
  CommonTable,
  EditableTable,
  PageTemplate,
  PageTemplateConfigBuilder,
  SearchForm,
  SmartBreadcrumb,
  type CommonFormRef,
  type FormFieldConfig,
  type SearchFieldConfig,
  type TableConfig,
} from 'any-front-ui';
import React, { useRef, useState } from 'react';

const AnyFrontUITest: React.FC = () => {
  const formRef = useRef<CommonFormRef>(null);
  const [formData, setFormData] = useState<any>({});
  const [tableData, setTableData] = useState<any[]>([
    { id: 1, name: '测试用户1', email: 'test1@example.com', status: 'active' },
    { id: 2, name: '测试用户2', email: 'test2@example.com', status: 'inactive' },
  ]);

  // 表单字段配置
  const formFields: FormFieldConfig[] = [
    {
      name: 'name',
      label: '姓名',
      type: 'input',
      rules: [{ required: true, message: '请输入姓名' }],
      span: 12,
    },
    {
      name: 'email',
      label: '邮箱',
      type: 'input',
      rules: [{ required: true, type: 'email', message: '请输入有效邮箱' }],
      span: 12,
    },
    {
      name: 'status',
      label: '状态',
      type: 'select',
      options: [
        { label: '激活', value: 'active' },
        { label: '禁用', value: 'inactive' },
      ],
      span: 12,
    },
    {
      name: 'birthDate',
      label: '出生日期',
      type: 'date',
      span: 12,
    },
    {
      name: 'description',
      label: '描述',
      type: 'textarea',
      span: 24,
    },
  ];

  // 搜索字段配置
  const searchFields: SearchFieldConfig[] = [
    {
      name: 'name',
      label: '姓名',
      type: 'input',
      placeholder: '请输入姓名',
    },
    {
      name: 'status',
      label: '状态',
      type: 'select',
      options: [
        { label: '激活', value: 'active' },
        { label: '禁用', value: 'inactive' },
      ],
    },
  ];

  // 表格配置
  const tableConfig: TableConfig = {
    columns: [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 80,
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (_, record: any) => (
          <span style={{ color: record.status === 'active' ? 'green' : 'red' }}>
            {record.status === 'active' ? '激活' : '禁用'}
          </span>
        ),
      },
    ],
    rowKey: 'id',
    props: {
      dataSource: tableData,
      pagination: {
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
    },
  };

  const handleFormSubmit = async () => {
    try {
      const values = await formRef.current?.validateFields();
      setFormData(values);
      message.success('表单验证通过！');
      console.log('表单数据:', values);
    } catch (error) {
      message.error('表单验证失败！');
    }
  };

  const handleFormReset = () => {
    formRef.current?.resetFields();
    setFormData({});
    message.info('表单已重置');
  };

  const handleSearch = (values: any) => {
    console.log('搜索条件:', values);
    message.info(`搜索条件: ${JSON.stringify(values)}`);
  };

  // 使用 PageTemplateConfigBuilder 构建页面配置
  const pageTemplateConfig = new PageTemplateConfigBuilder()
    .setPageConfig({
      title: 'any-front-ui 组件测试',
      breadcrumb: {
        items: [{ title: '首页', href: '/' }, { title: '组件测试' }],
      },
    })
    .setSearchConfig({
      fields: searchFields,
      onSearch: handleSearch,
    })
    .setTableConfig(tableConfig)
    .setFormConfig({
      fields: formFields,
    })
    .setActionConfig({
      permissions: {
        create: true,
        update: true,
        delete: true,
        view: true,
      },
    })
    .build();

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '24px' }}>
        <SmartBreadcrumb customItems={pageTemplateConfig.pageConfig?.breadcrumb?.items} />
      </div>

      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        {/* 表单测试 */}
        <Card title="CommonForm 组件测试" size="small">
          <CommonForm
            ref={formRef}
            fields={formFields}
            initialValues={{ status: 'active' }}
            onValuesChange={(changedValues, allValues) => {
              console.log('表单值变化:', changedValues, allValues);
            }}
          />
          <Space style={{ marginTop: '16px' }}>
            <Button type="primary" onClick={handleFormSubmit}>
              提交表单
            </Button>
            <Button onClick={handleFormReset}>重置表单</Button>
          </Space>
          {Object.keys(formData).length > 0 && (
            <div style={{ marginTop: '16px', padding: '12px', background: '#f5f5f5', borderRadius: '6px' }}>
              <strong>表单数据:</strong>
              <pre>{JSON.stringify(formData, null, 2)}</pre>
            </div>
          )}
        </Card>

        {/* 搜索表单测试 */}
        <Card title="SearchForm 组件测试" size="small">
          <SearchForm fields={searchFields} onSearch={handleSearch} onReset={() => message.info('搜索已重置')} />
        </Card>

        {/* 表格测试 */}
        <Card title="CommonTable 组件测试" size="small">
          <CommonTable
            {...tableConfig}
            title="用户列表"
            showAddButton={true}
            addButtonText="新增用户"
            onAdd={() => message.info('点击新增用户')}
          />
        </Card>

        {/* 可编辑表格测试 */}
        <Card title="EditableTable 组件测试" size="small">
          <EditableTable
            config={{
              columns: [
                {
                  title: '姓名',
                  dataIndex: 'name',
                  type: 'input',
                },
                {
                  title: '邮箱',
                  dataIndex: 'email',
                  type: 'input',
                },
                {
                  title: '状态',
                  dataIndex: 'status',
                  type: 'select',
                  options: [
                    { label: '激活', value: 'active' },
                    { label: '禁用', value: 'inactive' },
                  ],
                },
              ],
            }}
            value={tableData}
            onChange={(data) => {
              setTableData(data);
              message.success('表格数据已更新');
            }}
          />
        </Card>

        {/* PageTemplate 测试 - 使用配置构建器 */}
        <Card title="PageTemplate 组件测试 (使用配置构建器)" size="small">
          <PageTemplate {...pageTemplateConfig} />
        </Card>
      </Space>
    </div>
  );
};

export default AnyFrontUITest;
